package com.ubtechinc.cruzr.launcher2.widget;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.ubtechinc.cruzr.launcher2.R;
import com.ubtechinc.cruzr.launcher2.model.AppManger;

/**
 * 每个ITEM的父类，用来管理应用删除动画，点击动画等功能
 *
 * @author :ruiqiang
 */

@SuppressLint("ClickableViewAccessibility")
public class IclineRelaiveLayout extends RelativeLayout {
    //判断是否第三方应用ITEM
    public boolean isThirdApp = false;
    //判断是否是时钟和日历应用
    private boolean isClockItem = false;
    //进入删除模式时的动画
    private ValueAnimator mDeleteVA;

    private int downX;
    public boolean isAiniting = false;
    public Button mDeleteBtn;
    public String mAppName;
    private Context mContext;

    public IclineRelaiveLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        setClipToPadding(false);
        setClipChildren(false);
        setWillNotDraw(false);
    }

    public IclineRelaiveLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public IclineRelaiveLayout(Context context) {
        this(context, null);
    }


    /**
     * 用于Item处理item点击动画效果
     *
     * @params : [isdown]
     * @author :ruiqiang
     */
    private void setItemClickAnimator(boolean isdown) {
        setPivotY(getHeight() / 2);
        ValueAnimator va;
        if (isdown) {
            va = ValueAnimator.ofFloat(1f, 1.15f);
        } else {
            float currentr = getScaleX();
            va = ValueAnimator.ofFloat(currentr, 1f);
        }
        va.setInterpolator(new AccelerateDecelerateInterpolator());
        va.setDuration(50);
        va.addUpdateListener(new AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float r = (Float) animation.getAnimatedValue();
                setScaleX(r);
                setScaleY(r);
            }
        });
        va.start();
    }

    /**
     * 开始进入删除动画，主要实现无限放大缩小效果
     *
     * @params :
     * @author :ruiqiang
     */
    public void startDeleteAinimation() {
        if (isAiniting) {
            return;
        }
        showDeleteIcon();
        setItemClickAnimator(false);
        if (mDeleteVA == null) {
            mDeleteVA = ValueAnimator.ofFloat(1f, 0.95f, 1f);
        }
        mDeleteVA.setRepeatCount(ValueAnimator.INFINITE);
        mDeleteVA.setInterpolator(new TimeInterpolator() {

            @Override
            public float getInterpolation(float input) {
                return input;
            }
        });
        mDeleteVA.setDuration(1000);
        mDeleteVA.addUpdateListener(new AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float r = AppManger.get().getCurrentFloat();
                if (!AppManger.get().isAppDeleteState()) {
                    mDeleteVA.cancel();
                    r = 1f;
                    hideDeleteIcon();
                }
                setScaleX(r);
                setScaleY(r);
            }
        });
        mDeleteVA.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
            }

            public void onAnimationRepeat(Animator animation) {

            }
        });
        isAiniting = true;
        mDeleteVA.start();
    }

    /**
     * 停止删除动画，隐藏删除图标
     *
     * @params :
     * @author :ruiqiang
     */
    public void stopDeleteAinimation() {
        if (mDeleteVA != null) {
            mDeleteVA.cancel();
        }
        hideDeleteIcon();
        setScaleX(1f);
        setScaleY(1f);
        isAiniting = false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (AppManger.get().isAppDeleteState()) {
                    return super.onTouchEvent(event);
                }
                final int position[] = new int[2];
                getLocationInWindow(position);
                downX = (int) event.getX();
                setItemClickAnimator(true);
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                int d = (int) (event.getX() - downX);
                setItemClickAnimator(false);
                if (isClockItem && (Math.abs(d)) < 20) {
                    startActivityForY((int) event.getRawY());
                }
                break;
            default:
                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mDeleteBtn = (Button) findViewById(R.id.icondelete);
    }

    public void setClockItem(boolean clockItem) {
        isClockItem = clockItem;
    }

    /**
     * 闹钟应用根据点击的不同位置进入不同的应用
     *
     * @params : [y] 点击位置
     * @author :ruiqiang
     */
    private void startActivityForY(int y) {
        if (y > 830 && y < 960) {
            startGoalActivity("com.ubtechinc.cruzr.calendar", "com.ubtechinc.cruzr.calendar.activity.CalendarActivity");
        } else if (y > 150 && y < 830) {
            startGoalActivity("com.ubtechinc.cruzr.clock", "com.ubtechinc.cruzr.clock.MainActivity");
        }
    }

    /**
     * 打开目标应用
     *
     * @params : [packagename, activityname] 包名， 主页activity名
     * @author :ruiqiang
     */
    private void startGoalActivity(String packagename, String activityname) {
        try {
            ComponentName componentName = new ComponentName(packagename, activityname);
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.setComponent(componentName);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            mContext.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showDeleteIcon() {
        if (isThirdApp) {
            mDeleteBtn.setVisibility(View.VISIBLE);
            mDeleteBtn.bringToFront();
        }
    }

    private void hideDeleteIcon() {
        mDeleteBtn.setVisibility(View.INVISIBLE);
    }

    public void setThirdApp(boolean thirdApp) {
        isThirdApp = thirdApp;
    }

    public void setAppName(String name) {
        mAppName = name;
    }
}
